<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Your app title</title>
<link href="/customer_plat/public/stylesheets/webix_3.0.4.css"
	rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css"
	href="http://cdn.bootcss.com/font-awesome/4.4.0/css/font-awesome.css">
<link rel="stylesheet" type="text/css"
	href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.css">
<link href="/customer_plat/public/stylesheets/app.css" rel="stylesheet">
<script src="/customer_plat/public/javascripts/jquery.min.js"></script>
<script src="/customer_plat/public/javascripts/webix_3.0.4.js"
	type="text/javascript" charset="utf-8"></script>
<script src="/customer_plat/public/javascripts/vue.min.js"></script>
<script type="text/javascript">
	webix
			.ready(function() {
				var my_templaet = {
					template : "<span style='font-size:20px; font-weight:bold; color:#3498DB'; >排配产能详情</span>&nbsp;/&nbsp;&nbsp;PlanCompleteDetail",
					height : 45,
					borderless : true
				};
				var my_toolbar = {
					view : "toolbar",
					elements : [ {
						view : "datepicker",
						id : "start_date",
						timepicker : true,
						label : "起始日期",
						labelAlign : "right",
						name : "end",
						stringResult : true,
						format : "%Y-%m-%d",
						width : 240
					}, {
						view : "datepicker",
						id : "end_date",
						timepicker : true,
						label : "结束日期",
						labelAlign : "right",
						name : "end",
						stringResult : true,
						format : "%Y-%m-%d",
						width : 240
					}, {
						view : "button",
						value : "查询",
						width : 100,
						click : "select"
					} ]
				};
				var body = new webix.ui({
					container : "body",
					type : "line",
					id : "mylayout",
					rows : [ my_templaet, my_toolbar ],// ----rows结束----
				//----rows结束----
				});// ---webix.ui结束-
			});
</script>
</head>
<body style="background-color: #fff;">
	<div style="height: 45px; margin-top: 20px; margin-left: 5px;">
		<div id="body"></div>
	<div id="app" style="height: 800px;overflow-y:scroll;">
<div class='d-panel'>
  <table class="table table-striped table-bordered">
    <tr v-for="list in prolist" track-by="$index">
      <td><a @click="showdetail(list,$index)">{{list}}</a> 
        <div class='d-panel' id="proc" style="display:none">
          <table class="table table-striped table-bordered">
           <tr v-for="list in numlist" track-by="$index">
             <td>{{list.plan_name}}
             <td>{{list.date}}</td>
             <td>{{list.pr}}</td>
              <td v-for="col in columns" track-by="$index">{{list[col]}}</td>
           <tr>
          </table>
          <div class="btn btn-success" @click="outputexcel" style="float:right">
            output excel file</div>
        </div>
      </td>
    </tr>
  </table>
<div>
<script type="text/javascript">
 var prolist = [];
 var procelist = [];
 var planlist = [];
 var datelist = [];
 var classlist = [];
 var numlist = [];
 var numobj = {};
 var columns=[];
 var jsonlist =[]; //report.demodata.data;

function sortByKey(array, key) {
  return array.sort(function(a, b) {
     var x = a[key]; var y = b[key];
     return ((x < y) ? -1 : ((x > y) ? 1 : 0));
  });
}

function guid() {
  function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); }
  return [s4(), s4(), "-", s4(), "-", s4(), "-", s4(), "-", s4(), s4(), s4()].join("");
}

function getSessionId() {
  var id = sessionStorage.getItem('session_id');
  if (!id) {
    id = guid();
    sessionStorage.setItem('session_id', id);
  }
  return id;
}

 function apiCall(method, path, params, cb) {
	$.ajax({
		url:  path,
		method: method,
		cache: false,
		data: params,
		success: function(data) {
			cb(data);
		},
		error: function(xhr, status, data) {
			cb(jQuery.parseJSON(xhr.responseText));
		}
	});
}

function init() {
	var params = {};
	var url = "@{record.RecordAction.getPlanCompleteDetailInfo}";
	var start_date = $$("start_date").getValue();
	var end_date = $$("end_date").getValue();
	params["start_date"]= start_date.substring(0,10);
	params["end_date"] = end_date.substring(0,10);
	apiCall(
			'GET',
			url,
			params,
			function(data) {
     jsonlist=data;
     console.log(jsonlist)
     jsonlist.forEach(function(item,index) {
     if (prolist.indexOf(jsonlist[index].project_name) === -1) {
       prolist.push(jsonlist[index].project_name);
      }
     });
  })
};   

function fillTable(newarr){
 newarr.forEach(function(item,idx){
   var has = '0'
   numobj = {}
   numobj.date = item.date;
   numobj.pr = item.class_name;
   numobj.plan_name = item.plan_name;
    procelist.forEach(function(proce,index) {
      if (item.process_name === proce) {
         numobj['col'+index] = item.yield ;
         for (var i = 0; i < numlist.length; i++){
            if (numlist[i].date === numobj.date && numlist[i].pr === numobj.pr 
                && numlist[i]['col'+index]===''){
             numlist[i]['col'+index]=numobj['col'+index];
             has='1'
             break;
             } 
         }
      } else numobj['col'+index] ='';
     });
    if (has ==='0')
      numlist.push(numobj) 
   });
}
function uniencode(text)
{
    text = escape(text.toString()).replace(/\+/g, "%2B");
    var matches = text.match(/(%([0-9A-F]{2}))/gi);
    if (matches)
    {
        for (var matchid = 0; matchid < matches.length; matchid++)
        {
            var code = matches[matchid].substring(1,3);
            if (parseInt(code, 16) >= 128)
            {
                text = text.replace(matches[matchid], '%u00' + code);
            }
        }
    }
    text = text.replace('%25', '%u0025');
 
    return text;
} 
// _isIE11: function() {
//   var iev = 0;
//   var ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
//   var trident = !!navigator.userAgent.match(/Trident\/7.0/);
//   var rv = navigator.userAgent.indexOf("rv:11.0");

//   if (ieold) {
//     iev = Number(RegExp.$1);
//   }
//   if (navigator.appVersion.indexOf("MSIE 10") !== -1) {
//     iev = 10;
//   }
//   if (trident && rv !== -1) {
//     iev = 11;
//   }

//   return iev === 11;
// },

// _isEdge: function() {
//   return /Edge\/12/.test(navigator.userAgent);
// },

// _getDownloadUrl: function(text) {
//   var BOM = "\uFEFF";
//   // Add BOM to text for open in excel correctly
//   if (window.Blob && window.URL && window.URL.createObjectURL) {
//     var csvData = new Blob([BOM + text], { type: 'text/csv' });
//     return URL.createObjectURL(csvData);
//   } else {
//     return 'data:attachment/csv;charset=utf-8,' + BOM + encodeURIComponent(text);
//   }
// },

// download: function(filename, text) {
//   if (has('ie') && has('ie') < 10) {
//     // has module unable identify ie11 and Edge
//     var oWin = window.top.open("about:blank", "_blank");
//     oWin.document.write('sep=,\r\n' + text);
//     oWin.document.close();
//     oWin.document.execCommand('SaveAs', true, filename);
//     oWin.close();
//   }else if (has("ie") === 10 || this._isIE11() || this._isEdge()) {
//     var BOM = "\uFEFF";
//     var csvData = new Blob([BOM + text], { type: 'text/csv' });
//     navigator.msSaveBlob(csvData, filename);
//   } else {
//     var link = html.create("a", {
//       href: this._getDownloadUrl(text),
//       target: '_blank',
//       download: filename
//     }, this.domNode);
//     if (has('safari')) {
//       // # First create an event
//       var click_ev = document.createEvent("MouseEvents");
//       // # initialize the event
//       click_ev.initEvent("click", true /* bubble */ , true /* cancelable */ );
//       // # trigger the evevnt/
//       link.dispatchEvent(click_ev);
//     } else {
//       link.click();
//     }
//     html.destroy(link);
//   }
// }
 function select(){
	var vm = new Vue({
 		 el: '#app',
 		 data: {
  	  numlist:[],
      columns:[],
      prolist: prolist,
      procelist:[],
  },   
  methods: {
     showdetail(list,proc_idx) {
      datelist = [];
      jsonlist.forEach(function(item,index) {
        if (datelist.indexOf(item.date) === -1 && item.project_name === list) {
          datelist.push(item.date);
        };
        if (classlist.indexOf(item.class_name) === -1 && item.project_name === list) {
          classlist.push(item.class_name);
        };
  
      });
     console.log(classlist)
     var newarr =jsonlist.filter(function(pitem) {
       return pitem.project_name === list; 
     });
     procelist = [];
     classlist = [];

     newarr.forEach(function(item,index) {
       if (procelist.indexOf(item.process_name) === -1) {
        procelist.push(item.process_name);
       };
     })
     numlist=[];
     numobj={};
     columns=[];
     numobj.date='日期'
     numobj.pr = '班别名称';
     numobj.plan_name = "计划名称";
     procelist.forEach(function(proc,idx){  
       numobj['col'+idx] = proc;
       columns.push('col'+idx);
     });
     numlist.push(numobj)
     procelist.forEach(function(proc,index){
       datelist.forEach(function(date,idx){
          var marr = jsonlist.filter(function(item) {
           return item.process_name === proc && item.date === date ;
         });
         fillTable(marr)
       })
     });
     
  //   console.log(JSON.stringify(numlist)); 
     //clcSum(procelist,numlist) //sum
     this.numlist=numlist;
     this.columns=columns; 
     var objlist = document.querySelectorAll('#proc');
     console.log(objlist.length)
     for (var i=0;i<objlist.length;i++) {
       if (i===proc_idx) {
         if (objlist[i].style.display == 'block')
           objlist[i].style.display = 'none';
         else objlist[i].style.display = 'block'
        }
       else objlist[i].style.display = 'none';
     };
     
   },
    init:init,
    outputexcel:function(){
      JSONToCSVConvertor(numlist,'排配产能详情',true);
    }
  },
  ready:function () { 
  	this.init()
  }
})
 }
</script>
</body>
</html>
